package sam.learn.biz.datasource.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sam.learn.biz.datasource.controller.dto.DataSourceInfoVo;
import sam.learn.biz.datasource.repo.entity.DatasourceInfo;
import sam.learn.biz.datasource.service.DatasourceInfoService;
import sam.learn.framework.dynamicDataSource.DbDynamicDataSourceLoader;
import sam.learn.framework.web.ResponseResult;

@RestController
@RequestMapping("/datasource")
public class DatasourceInfoController {

    @Autowired
    private DatasourceInfoService datasourceInfoService;

    @Autowired
    private DbDynamicDataSourceLoader dbDynamicDataSourceLoader;

    @GetMapping("/queryByRegionCode")
    public DataSourceInfoVo queryByRegionCode(String regionCode) {
        DatasourceInfo datasourceInfo = datasourceInfoService.getDatasourceBy(regionCode);
        return DataSourceInfoVo.from(datasourceInfo);
    }

    @DeleteMapping("/deleteByRegionCode")
    public ResponseResult<String> deleteDatasource(String regionCode) {
        dbDynamicDataSourceLoader.removeDatasourceBy(regionCode);
        return ResponseResult.success("ok");
    }


    @PostMapping("/add")
    public DatasourceInfo addDatasourceInfo(
            String regionCode,
            String aliasName,
            String ip,
            String port,
            String schema,
            String user,
            String pwd,
            String brand
    ) {
        DatasourceInfo datasourceInfo = DatasourceInfo.Builder.newBuilder()
                .regionCode(regionCode)
                .aliasName(aliasName)
                .ip(ip)
                .port(port)
                .schema(schema)
                .user(user)
                .pwd(pwd)
                .brand(brand)
                .build();
        return datasourceInfoService.addDatasource(datasourceInfo);
    }
}
